package com.example.huixue.service;

import com.example.huixue.common.PageResult;
import com.example.huixue.entity.Resource;
import com.example.huixue.mapper.ResourceMapper;
import com.example.huixue.mapper.CommentMapper;
import com.example.huixue.mapper.FavoriteMapper;
import com.example.huixue.mapper.RatingMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class ResourceService {
    
    @Autowired
    private ResourceMapper resourceMapper;
    
    @Autowired
    private CommentMapper commentMapper;
    
    @Autowired
    private FavoriteMapper favoriteMapper;
    
    @Autowired
    private RatingMapper ratingMapper;
    
    @Value("${file.upload.path:./uploads/}")
    private String uploadPath;
    
    /**
     * 分页查询资源
     */
    public PageResult<Resource> getResourcesWithPagination(int page, int size, String keyword, 
                                                          Long categoryId, String fileType, String sortBy) {
        int offset = (page - 1) * size;
        
        // 查询资源列表
        List<Resource> resources = resourceMapper.selectResourcesWithPagination(
            offset, size, keyword, categoryId, fileType, sortBy);
        
        // 查询总数
        long total = resourceMapper.countResources(keyword, categoryId, fileType);
        
        return new PageResult<>(resources, total, page, size);
    }
    
    /**
     * 根据ID获取资源详情
     */
    public Resource getResourceById(Long resourceId) {
        Resource resource = resourceMapper.selectById(resourceId);
        if (resource != null) {
            // 增加查看次数
            resourceMapper.incrementViewCount(resourceId);
        }
        return resource;
    }
    
    /**
     * 获取相关资源推荐
     */
    public List<Resource> getRelatedResources(Long resourceId) {
        // 根据当前资源的分类获取相关资源
        Resource currentResource = resourceMapper.selectById(resourceId);
        if (currentResource != null) {
            return resourceMapper.selectByCategoryId(currentResource.getCategoryId(), 6); // 获取6个相关资源
        }
        return resourceMapper.selectLatestResources(6); // 如果没有找到当前资源，返回最新资源
    }
    
    /**
     * 增加浏览量
     */
    public void incrementViewCount(Long resourceId) {
        resourceMapper.incrementViewCount(resourceId);
    }
    
    /**
     * 获取资源统计信息
     */
    public Map<String, Object> getResourceStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 总资源数
        long totalResources = resourceMapper.countAllResources();
        stats.put("totalResources", totalResources);
        
        // 已审核资源数
        long approvedResources = resourceMapper.countResourcesByStatus("APPROVED");
        stats.put("approvedResources", approvedResources);
        
        // 待审核资源数
        long pendingResources = resourceMapper.countResourcesByStatus("PENDING");
        stats.put("pendingResources", pendingResources);
        
        // 被拒绝的资源数
        long rejectedResources = resourceMapper.countResourcesByStatus("REJECTED");
        stats.put("rejectedResources", rejectedResources);
        
        // 总下载量
        long totalDownloads = resourceMapper.getTotalDownloads();
        stats.put("totalDownloads", totalDownloads);
        
        // 总浏览量
        long totalViews = resourceMapper.getTotalViews();
        stats.put("totalViews", totalViews);
        
        return stats;
    }
    
    /**
     * 审核通过资源
     */
    public void approveResource(Long resourceId) {
        resourceMapper.updateResourceStatus(resourceId, "APPROVED");
    }
    
    /**
     * 拒绝资源
     */
    public void rejectResource(Long resourceId, String reason) {
        resourceMapper.updateResourceStatus(resourceId, "REJECTED");
        // 可以在这里记录拒绝原因到数据库
        // resourceMapper.insertRejectReason(resourceId, reason);
    }
    
    /**
     * 上传资源文件
     */
    public Resource uploadResource(MultipartFile file, String title, String description, Long categoryId, Long uploaderId) throws IOException {
        // 创建上传目录 - 使用绝对路径
        String absoluteUploadPath = uploadPath;
        if (!uploadPath.startsWith("/") && !uploadPath.contains(":")) {
            // 如果是相对路径，转换为绝对路径
            absoluteUploadPath = System.getProperty("user.dir") + File.separator + uploadPath;
        }
        
        File uploadDir = new File(absoluteUploadPath);
        if (!uploadDir.exists()) {
            boolean created = uploadDir.mkdirs();
            if (!created) {
                throw new IOException("无法创建上传目录: " + uploadDir.getAbsolutePath());
            }
        }
        
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String filename = UUID.randomUUID().toString() + extension;
        
        // 保存文件
        File targetFile = new File(uploadDir, filename);
        file.transferTo(targetFile);
        
        // 创建资源记录
        Resource resource = new Resource();
        resource.setTitle(title);
        resource.setDescription(description);
        resource.setFilePath(targetFile.getAbsolutePath());
        resource.setFileSize(file.getSize());
        resource.setFileType(getFileType(originalFilename));
        resource.setCategoryId(categoryId);
        resource.setUploaderId(uploaderId);
        resource.setStatus("PENDING"); // 默认待审核状态
        resource.setCreatedAt(LocalDateTime.now());
        resource.setUpdatedAt(LocalDateTime.now());
        
        // 保存到数据库
        resourceMapper.insert(resource);
        
        return resource;
    }
    
    /**
     * 根据文件名获取文件类型
     */
    private String getFileType(String filename) {
        if (filename == null) return "unknown";
        
        String extension = filename.toLowerCase();
        if (extension.endsWith(".pdf")) return "pdf";
        if (extension.endsWith(".doc") || extension.endsWith(".docx")) return "doc";
        if (extension.endsWith(".ppt") || extension.endsWith(".pptx")) return "ppt";
        if (extension.endsWith(".xls") || extension.endsWith(".xlsx")) return "xls";
        if (extension.endsWith(".mp4") || extension.endsWith(".avi") || extension.endsWith(".mkv")) return "video";
        if (extension.endsWith(".mp3") || extension.endsWith(".wav")) return "audio";
        if (extension.endsWith(".jpg") || extension.endsWith(".jpeg") || extension.endsWith(".png") || extension.endsWith(".gif")) return "image";
        if (extension.endsWith(".zip") || extension.endsWith(".rar") || extension.endsWith(".7z")) return "archive";
        
        return "other";
    }
    
    /**
     * 创建资源
     */
    public Resource createResource(Resource resource) {
        resource.setCreatedAt(LocalDateTime.now());
        resource.setUpdatedAt(LocalDateTime.now());
        resourceMapper.insert(resource);
        return resource;
    }
    
    /**
     * 更新资源
     */
    public Resource updateResource(Resource resource) {
        resource.setUpdatedAt(LocalDateTime.now());
        resourceMapper.update(resource);
        return resource;
    }
    
    /**
     * 删除资源（级联删除相关数据）
     */
    public boolean deleteResource(Long resourceId) {
        try {
            // 1. 删除相关的评论
            commentMapper.deleteByResource(resourceId);
            
            // 2. 删除相关的收藏记录
            favoriteMapper.deleteByResource(resourceId);
            
            // 3. 删除相关的评分记录
            ratingMapper.deleteByResource(resourceId);
            
            // 4. 获取资源信息以删除物理文件
            Resource resource = resourceMapper.selectById(resourceId);
            if (resource != null && resource.getFilePath() != null) {
                try {
                    // 删除物理文件
                    File file = new File(resource.getFilePath());
                    if (file.exists()) {
                        file.delete();
                    }
                } catch (Exception e) {
                    // 日志记录但不影响数据库删除
                    System.err.println("删除文件失败: " + e.getMessage());
                }
            }
            
            // 5. 最后删除资源记录
            return resourceMapper.delete(resourceId) > 0;
        } catch (Exception e) {
            System.err.println("删除资源失败: " + e.getMessage());
            throw new RuntimeException("删除资源失败: " + e.getMessage());
        }
    }
    
    /**
     * 增加下载次数
     */
    public void incrementDownloadCount(Long resourceId) {
        resourceMapper.incrementDownloadCount(resourceId);
    }
    
    /**
     * 更新资源评分
     */
    public void updateResourceRating(Long resourceId, Double rating) {
        resourceMapper.updateRating(resourceId, rating);
    }
    
    /**
     * 获取热门资源（下载最多、收藏最多、阅读最多的各一个）
     */
    public List<Resource> getPopularResources(int limit) {
        List<Resource> popularResources = new ArrayList<>();
        
        // 获取下载最多的资源
        List<Resource> mostDownloaded = resourceMapper.selectResourcesWithPagination(0, 1, null, null, null, "downloadCount");
        if (!mostDownloaded.isEmpty()) {
            popularResources.add(mostDownloaded.get(0));
        }
        
        // 获取阅读最多的资源（按浏览量排序）
        List<Resource> mostViewed = resourceMapper.selectResourcesWithPagination(0, 1, null, null, null, "viewCount");
        if (!mostViewed.isEmpty()) {
            Resource mostViewedResource = mostViewed.get(0);
            // 避免重复添加同一个资源
            if (popularResources.stream().noneMatch(r -> r.getResourceId().equals(mostViewedResource.getResourceId()))) {
                popularResources.add(mostViewedResource);
            }
        }
        
        // 获取评分最高的资源
        List<Resource> highestRated = resourceMapper.selectResourcesWithPagination(0, 1, null, null, null, "rating");
        if (!highestRated.isEmpty()) {
            Resource highestRatedResource = highestRated.get(0);
            // 避免重复添加同一个资源
            if (popularResources.stream().noneMatch(r -> r.getResourceId().equals(highestRatedResource.getResourceId()))) {
                popularResources.add(highestRatedResource);
            }
        }
        
        // 如果还没有足够的资源，补充一些热门资源
        if (popularResources.size() < 3) {
            List<Resource> additionalResources = resourceMapper.selectPopularResources(5);
            for (Resource resource : additionalResources) {
                if (popularResources.size() >= 3) break;
                if (popularResources.stream().noneMatch(r -> r.getResourceId().equals(resource.getResourceId()))) {
                    popularResources.add(resource);
                }
            }
        }
        
        return popularResources;
    }
    
    /**
     * 获取最新资源
     */
    public List<Resource> getLatestResources(int limit) {
        return resourceMapper.selectLatestResources(limit);
    }
    
    /**
     * 根据用户ID获取上传的资源
     */
    public List<Resource> getResourcesByUploaderId(Long uploaderId) {
        return resourceMapper.selectByUploaderId(uploaderId);
    }
    
    /**
     * 管理员分页查询资源（包含所有状态）
     */
    public PageResult<Resource> getAdminResourcesWithPagination(int page, int size, String keyword, 
                                                               Long categoryId, String fileType, String status, String sortBy) {
        int offset = (page - 1) * size;
        
        // 查询资源列表（管理员可以看到所有状态的资源）
        List<Resource> resources = resourceMapper.selectAdminResourcesWithPagination(
            offset, size, keyword, categoryId, fileType, status, sortBy);
        
        // 查询总数
        long total = resourceMapper.countAdminResources(keyword, categoryId, fileType, status);
        
        return new PageResult<>(resources, total, page, size);
    }
    
    /**
     * 记录下载统计
     */
    public void recordDownload(Long resourceId, Long userId) {
        // 增加下载次数
        incrementDownloadCount(resourceId);
        
        // 可以在这里添加下载记录到download_records表
        // 如果有DownloadRecordMapper的话可以记录详细的下载记录
        // downloadRecordMapper.insertDownloadRecord(userId, resourceId, LocalDateTime.now());
    }
    
    /**
     * 批量审核通过资源
     */
    public void batchApproveResources(List<Long> resourceIds) {
        for (Long resourceId : resourceIds) {
            resourceMapper.updateResourceStatus(resourceId, "APPROVED");
        }
    }
    
    /**
     * 批量拒绝资源
     */
    public void batchRejectResources(List<Long> resourceIds) {
        for (Long resourceId : resourceIds) {
            resourceMapper.updateResourceStatus(resourceId, "REJECTED");
        }
    }
    
    /**
     * 批量删除资源
     */
    public void batchDeleteResources(List<Long> resourceIds) {
        for (Long resourceId : resourceIds) {
            deleteResource(resourceId);
        }
    }
} 